<template>
    <div>
        <Card>
            <Row>
                <Button type="primary" icon="md-add" size="large" @click="appearModal()">新增</Button>
            </Row>
            <Row>
                <el-table stripe border :data="tableData" @expand-change="queryDtlInfo">
                    <template slot="empty">暂无数据</template>

                    <el-table-column type="expand">
                        <template slot-scope="props">
                            <el-table :data="dtlInfoList" border style="width: 100%">
                                <el-table-column label="物资类别" prop="materialClass"></el-table-column>
                                <el-table-column label="物资编号" prop="materialCode"></el-table-column>
                                <el-table-column label="物资名称" prop="materialName"></el-table-column>
                                <el-table-column label="单位" prop="materialUnit"></el-table-column>
                                <el-table-column label="规格" prop="materialSpecifications"></el-table-column>
                                <el-table-column label="系统单价" prop="purchasePrice"></el-table-column>
                                <el-table-column label="安全库存量" prop="safetyStock"></el-table-column>
                                <el-table-column label="实际库存量" prop="stockNumber"></el-table-column>
                                <el-table-column label="采购单价" prop="unitPurchasePrice"></el-table-column>
                                <el-table-column label="采购数量" prop="purchaseQuantity"></el-table-column>
                                <el-table-column label="金额" prop="totalPurchasePrice"></el-table-column>
                                <el-table-column label="供应商" prop="supplierName"></el-table-column>
                            </el-table>
                        </template>
                    </el-table-column>
                    <el-table-column label="采购订单号" prop="purchasingOrderNumber"></el-table-column>
                    <el-table-column label="仓库" prop="warehouseName"></el-table-column>
                    <el-table-column label="采购日期" prop="procurementDate"></el-table-column>
                    <el-table-column label="申请人" prop="applicantName"></el-table-column>
                    <el-table-column label="审核人" prop="auditorName"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button size="mini" type="danger" @click="openDelete(scope.row.purchasingOrderNumber)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </Row>
            <Page style="margin: 10px 0;" :total="pageTotal" :current="pageNum" :page-size="pageSize" show-total
                  show-sizer show-elevator @on-change="handlePage" @on-page-size-change='handlePageSize'>
            </Page>
        </Card>
        <!--新增采购申请-->
        <Modal v-model="modalVisible" :title="modalTitle" width="80%" class="ly-form-item">
            <el-form :model="purchasing" :rules="rules" ref="purchasingForm" :inline="true">
                <el-form-item label="采购订单号" prop="purchasingOrderNumber">
                    <el-input @blur="checkOrderNum" v-model="purchasing.purchasingOrderNumber"></el-input>
                </el-form-item>
                <el-form-item label="仓库名称">
                    <el-select value-key="id" v-model="value">
                        <el-option v-for="item in warehouseList" :key="item.id" :value="item" :label="item.warehouseName">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="采购日期">
                    <DatePicker v-model="purchasing.procurementDate" format="yyyy-MM-dd" placement="bottom-end"
                                placeholder="请选择采购日期" style="width: 250px"></DatePicker>
                </el-form-item>
                <el-form-item label="申请人">
                    <el-input v-model="purchasing.applicantName" @focus="alertMemberDialog(1)"
                              placeholder="请选择"></el-input>
                </el-form-item>
                <el-form-item label="审核人">
                    <el-input v-model="purchasing.auditorName" @focus="alertMemberDialog(2)"
                              placeholder="请选择"></el-input>
                </el-form-item>
                <el-form-item label="物资详情">
                    <el-table :data="purchasing.dtlList" border style="width: 100%">
                        <el-table-column label="" width="50">
                            <template slot-scope="scope">
                                <i class="el-icon-remove" @click="delMaterialData(scope.$index)"></i>
                            </template>
                        </el-table-column>
                        <el-table-column prop="className" label="物资类别" width="120"></el-table-column>
                        <el-table-column prop="code" label="物资编号" width="120"></el-table-column>
                        <el-table-column prop="name" label="物资名称" width="100"></el-table-column>
                        <el-table-column prop="unit" label="单位" width="80"></el-table-column>
                        <el-table-column prop="specifications" label="规格" width="80"></el-table-column>
                        <el-table-column prop="purchasePrice" label="系统单价" width="80"></el-table-column>
                        <el-table-column prop="safetyStock" label="安全库存量" width="80"></el-table-column>
                        <el-table-column prop="actualStock" label="实际库存量" width="80"></el-table-column>
                        <el-table-column label="采购单价">
                            <template slot-scope="scope" width="120">
                                <el-input v-model="scope.row.unitPurchasePrice" placeholder="请输入价格"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="采购数量" width="120">
                            <template slot-scope="scope">
                                <el-input v-model="scope.row.purchaseQuantity" placeholder="请输入数量"
                                ></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="金额" width="120">
                            <template slot-scope="scope">
                                <el-input disabled v-model="scope.row.totalPurchasePrice"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="supplierName" label="供应商" width="180">
                            <template slot-scope="scope">
                                <el-select v-model="scope.row.supplierName" placeholder="请选择" clearable filterable>
                                    <el-option v-for="item in supplierList" :key="item.id" :value="item.supplierName" :label="item.supplierName">

                                    </el-option>
                                </el-select>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-button type="text" @click="addMaterialData">+ 添加</el-button>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <Button type="primary" @click="submitUpload('purchasingForm')">确定</Button>
            </div>
        </Modal>
        <!--选择物资-->
        <Modal v-model="materialSelectVisible">
            <el-select value-key="id" v-model="materialValue" @change="materialChange" clearable filterable>
                <el-option v-for="item in materialList" :key="item.id" :value="item" :label="item.name">

                </el-option>
            </el-select>
        </Modal>
        <!--人员选择-->
        <MemberSelector :data-tree="treeList" mode="SingleMember" :data-member="memberList"
                        ref="memberSelector" @treenodeclick="treeNodeClick" @affirmative="confirmMember">
        </MemberSelector>
    </div>
</template>

<script>
    import Treeselect from "@riophae/vue-treeselect";
    import MemberSelector from "../../components/member-selector/selector";
    import moment from "moment"

    export default {
        components: {
            Treeselect,
            MemberSelector,
        },

        data() {
            return {
                pageNum: 1,
                pageSize: 10,
                pageTotal: 0,
                orderNumExist:0,
                memberType: "",
                modalTitle: "",
                modalVisible: false,
                materialSelectVisible: false,


                tableData: [],
                warehouseList: [],
                supplierList:[],
                materialList: [],
                treeList: [],
                memberList: [],
                dtlInfoList:[],

                value: {},
                materialValue: {},
                purchasing: {
                    applicantName: "",
                    auditorName: "",
                    dtlList: [],
                },
                rules: {
                    purchasingOrderNumber: [
                        {
                            required: true,
                            message: "请输入采购订单号",
                        }
                    ],
                },
            }

        },
        created: function () {
            this.getWarehouse();
            this.getSuppliers();
            this.getMaterials();
            this.getTreeData();
            this.loadData();
        },
        watch: {
            purchasing: {
                deep: true,
                handler(val) {
                    this.setTotal();
                }
            },
        },
        methods: {
            loadData(){
                this.getRequest("/api/prc/purchasings?pageNum="+this.pageNum+"&pageSize="+this.pageSize).then(resp=>{
                    if (resp.code==20000){
                        this.tableData=resp.data.list;
                        this.pageTotal=resp.data.total;
                    }
                });
            },
            alertMemberDialog: function (type) {
                this.memberType = type;
                this.$refs.memberSelector.showDialog();
            },
            getWarehouse() {
                this.getRequest("/api/whsc/warehouses?pageNum=" + this.pageNum + "&pageSize=" + this.pageSize).then(resp => {
                    if (resp.code == 20000) {
                        this.warehouseList = resp.data.list;
                    }
                });
            },
            getSuppliers(){
                this.getRequest("/api/spsc/suppliers?pageNum=" + this.pageNum + "&pageSize=" + this.pageSize).then(resp => {
                    if (resp.code == 20000) {
                        this.supplierList = resp.data.list;
                    }
                });
            },
            getMaterials() {
                this.getRequest("/api/msc/materials?pageNum=" + this.pageNum + "&pageSize=" + this.pageSize).then(resp => {
                    if (resp.code == 20000) {
                        this.materialList = resp.data.list;
                    }
                });
            },
            queryDtlInfo(row,expandedRows){
                this.dtlInfoList=[];
                if (expandedRows.length > 1) {
                    expandedRows.shift();
                    this.getRequest("/api/prc/details?orderNumber="+row.purchasingOrderNumber).then(resp => {
                        if (resp.code == 20000) {
                            this.dtlInfoList = resp.data;
                        }
                    });
                } else {
                    this.getRequest("/api/prc/details?orderNumber="+row.purchasingOrderNumber).then(resp => {
                        if (resp.code == 20000) {
                            this.dtlInfoList = resp.data;
                        }
                    });
                }
            },
            materialChange(obj) {
                this.purchasing.dtlList.push({
                    materialId:obj.id,
                    className:obj.className,
                    code:obj.code,
                    name:obj.name,
                    unit:obj.unit,
                    specifications:obj.specifications,
                    purchasePrice:obj.purchasePrice,
                    safetyStock:obj.safetyStock,
                    supplierName:"",
                });
                this.materialSelectVisible=false;
            },
            //获取部门信息
            getTreeData() {
                this.postRequest("/api/manageHR/getCompany").then(res => {
                    if (res.code == 20000) {
                        this.treeList = res.data;
                    } else {
                        this.$Message.error({
                            content: res.message,
                            duration: 5
                        });
                    }
                });
            },
            //部门点击选择
            treeNodeClick: function (data) {
                this.getMemberList(data);
            },
            //获取成员
            getMemberList(data) {
                const params = {};
                params.pageNum = null;
                if (data) {
                    params.companyId = data.companyId;
                }
                //与后台交换数据
                this.postRequest("/api/manageHR/userLoadData", params).then(res => {
                    if (res.code == 20000) {
                        const tmpList = [];
                        res.data.list.forEach(function (c) {
                            const list = c;
                            list.label = (c.name);
                            tmpList.push(list);
                        });
                        this.memberList = tmpList;
                    }
                });
            },
            checkOrderNum(){
                this.getRequest("/api/prc/check?orderNum="+this.purchasing.purchasingOrderNumber).then(resp=>{
                    console.info(resp);
                    if (resp.code==20000){
                        if (resp.data!=0){
                            this.$Message.error("当前订单号已存在");
                            this.orderNumExist=1;
                        }else {
                            this.orderNumExist=0;
                        }
                    }
                });
            },
            confirmMember(data) {
                if (this.memberType == 1) {
                    this.purchasing.applicantId = data[0].id;
                    this.purchasing.applicantName = data[0].name;
                } else if (this.memberType == 2) {
                    this.purchasing.auditorId = data[0].id;
                    this.purchasing.auditorName = data[0].name;
                }
            },
            submitUpload(purchasingForm) {
                this.$refs[purchasingForm].validate((valid) => {
                    if (valid) {
                        if (this.orderNumExist!=0){
                            this.$Message.error("当前订单号已存在，求修改后在提交");
                            return;
                        }else if (this.purchasing.dtlList.length==0){
                            this.$Message.error("请添加物资");
                            return;
                        } else {
                            this.purchasing.warehouseId = this.value.id;
                            this.purchasing.warehouseName = this.value.warehouseName;
                            if (this.purchasing.procurementDate){
                                this.purchasing.procurementDate=moment(this.purchasing.procurementDate).format("YYYY-MM-DD");
                            }
                            this.postJsonRequest("/api/prc/purchasing",this.purchasing).then(resp=>{
                                console.info(resp);
                                if (resp.code==20000){
                                    this.modalVisible=false;
                                    this.purchasing=[],
                                        this.loadData();
                                }
                            });
                        }
                    }
                });
            },
            appearModal(row) {
                if (row == null) {
                    this.modalTitle = "新增";
                    this.purchasing.dtlList = [];
                } else {
                    this.modalTitle = "修改";
                }
                this.modalVisible = true;
            },
            addMaterialData: function () {
                this.materialSelectVisible = true;
            },
            delMaterialData: function (index) {
                this.purchasing.dtlList.splice(index, 1);
            },
            openDelete(orderNum){
                this.$Modal.confirm({
                    title: '提示',
                    content: '确定删除该条数据？',
                    onOk: () => {
                        this.getRequest("/api/prc/purchasing?orderNum=" + orderNum).then(resp => {
                            this.tableLoading = false;
                            if (resp.code == 20000) {
                                this.$Message.success("删除成功!");
                                this.pageNum = 1;
                                this.loadData();
                            } else {
                                this.$Message.error({
                                    content: resp.message,
                                    duration: 5
                                });
                            }
                        });
                    },
                });
            },
            handlePage(value) {
                this.pageNum = value;
                this.loadData();
            },
            handlePageSize(value) {
                this.pageSize = value;
                this.loadData();
            },
            setTotal: function () {
                for (let item of this.purchasing.dtlList) {
                    if (item.unitPurchasePrice && item.purchaseQuantity) {
                        item.totalPurchasePrice = item.unitPurchasePrice * item.purchaseQuantity;
                    } else {
                        item.totalPurchasePrice = 0
                    }
                }
            },
        },
    }
</script>

<style>
    .ly-form-item .el-form--inline .el-form-item {
        display: block;
    }
</style>
